package com.chaos.grpcclient;

import com.chaos.remoting.grpc.User;
import com.chaos.remoting.grpc.UserServiceGrpc;
import io.grpc.Channel;
import net.devh.springboot.autoconfigure.grpc.client.GrpcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;

/**
 * @author liaopeng
 * @title: UserController
 * @projectName grpc-demo
 * @description: TODO
 * @date 2021/9/2下午4:11
 */
@RestController
public class UserController {

    @GrpcClient("local-grpc-server")
    private Channel serverChannel;

    @RequestMapping("/register")
    public String register(@RequestParam(defaultValue = "liaopeng") String param) {
        UserServiceGrpc.UserServiceBlockingStub stub = UserServiceGrpc.newBlockingStub(serverChannel);
        User.UserRequest request = User.UserRequest.newBuilder().setName("chaos").build();
        User.UserResponse response = stub.register(request);
        return response.getMsg();
    }

    @RequestMapping("/queryAll")
    public String queryAll(@RequestParam(defaultValue = "liaopeng") String param) {
        UserServiceGrpc.UserServiceBlockingStub stub = UserServiceGrpc.newBlockingStub(serverChannel);
        User.UserRequest request = User.UserRequest.newBuilder().setName("chaos").build();
        Iterator<User.UserResponse> responseIterator = stub.queryAll(request);
        StringBuilder sb = new StringBuilder();
        while (responseIterator.hasNext()){
            sb.append(responseIterator.next()).append(",");
        }
        return sb.toString();
    }
}
